package com.fanyouzhao.ehome2.admin.interceptor;


import com.fanyouzhao.ehome2.admin.annotation.NeedsLogin;
import com.fanyouzhao.ehome2.admin.annotation.NoNeedsLogin;
import com.fanyouzhao.ehome2.admin.exception.BusinessException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 权限拦截器
 * @author: fanyouzhao
 * @date: 16:39 2021/6/22
 */
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 操作执行前拦截的操作
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o                   方法对象
     * @return 是否拦截, true表示放行, false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (o instanceof HandlerMethod){
            // 通过HandlerMethod类型获取参数o的方法特征，获取Method方法
            Method method = ((HandlerMethod) o).getMethod();
            // 通过对象o获取Handler所在控制器的Class
            Class<?> clazz = ((HandlerMethod) o).getBeanType();
            boolean annoFromMethod = method.isAnnotationPresent(NeedsLogin.class);
            boolean annoFromType = clazz.isAnnotationPresent(NeedsLogin.class);
            boolean annoNoLoginFromMethod = method.isAnnotationPresent(NoNeedsLogin.class);
            // 判断该方法或者类上有无NeedsLogin注解，有此注解就需要做权限判断
            if ((annoFromMethod||annoFromType)&&!annoNoLoginFromMethod) {
                //权限判断
                System.out.println(method.getName() + "方法需要权限");
                //判断session是否为空（即是否为已登录用户，实际上并不严格）
                if (httpServletRequest.getSession().getAttribute("phone")!=null){
                    System.out.println("有session,登录成功");
                    return true;
                }else {
                    throw new BusinessException("无访问权限");
                }
            } else {
                return true;
            }
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
